<template>
  <!-- eslint-disable vue/no-v-html -->
  <div class="auth-wrapper d-flex align-center justify-center pa-4">
    <VCard
      class="auth-card pa-4 pt-7"
      max-width="448"
    >
      <VCardItem class="justify-center">
        <NuxtLink
          to="/"
          class="d-flex align-center gap-3"
        >
          <img :src="logo" class="logo">
          <!-- <h2 class="font-weight-medium text-2xl text-uppercase">
            发卡系统
          </h2> -->
        </NuxtLink>
      </VCardItem>

      <VCardText class="pt-2">
        <h4 class="text-h4 mb-1">
          欢迎使用Cffk发卡 👋🏻
        </h4>
        <p class="mb-0">
          请登录您的账号
        </p>
      </VCardText>

      <VCardText>
        <VForm @submit.prevent="() => {}">
          <VRow>
            <!-- email -->
            <VCol cols="12">
              <VTextField
                :id="useId()"
                v-model="form.email"
                label="Email"
                type="email"
              />
            </VCol>

            <!-- form.password -->
            <VCol cols="12">
              <VTextField
                :id="useId()"
                v-model="form.password"
                label="Password"
                placeholder="············"
                :type="showPassword ? 'text' : 'password'"
                autocomplete="password"
                :append-inner-icon="showPassword ? 'ri-eye-off-line' : 'ri-eye-line'"
                @click:append-inner="showPassword = !showPassword"
              />

              <!-- remember me checkbox -->
              <div class="d-flex align-center justify-space-between flex-wrap my-6">
                <VCheckbox
                  :id="useId()"
                  v-model="form.remember"
                  label="Remember me"
                />

                <a
                  class="text-primary"
                  href="javascript:void(0)"
                >
                  Forgot Password?
                </a>
              </div>

              <!-- login button -->
              <VBtn
                block
                type="submit"
                @click="login"
                :loading="loading"
              >
                Login
              </VBtn>
            </VCol>

            <!-- create account -->
            <VCol
              cols="12"
              class="text-center text-base"
            >
              <span>New on our platform?</span>
              <NuxtLink
                class="text-primary ms-2"
                to="/register"
              >
                Create an account
              </NuxtLink>
            </VCol>

            <VCol
              cols="12"
              class="d-flex align-center"
            >
              <VDivider />
              <span class="mx-4">or</span>
              <VDivider />
            </VCol>

            <!-- auth providers -->
            <VCol
              cols="12"
              class="text-center"
            >
              <AuthProvider />
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
    </VCard>

    <VImg
      class="auth-footer-start-tree d-none d-md-block"
      :src="authV1Tree"
      :width="250"
    />

    <VImg
      :src="authV1Tree2"
      class="auth-footer-end-tree d-none d-md-block"
      :width="350"
    />

    <!-- bg img -->
    <VImg
      class="auth-footer-mask d-none d-md-block"
      :src="authThemeMask"
    />
  </div>
</template>

<script setup>
import { useTheme } from 'vuetify'
import AuthProvider from '~/view/authentication/AuthProvider.vue'
import logo from 'public/logo.png'
import authV1MaskDark from '~/assets/images/pages/auth-v1-mask-dark.png'
import authV1MaskLight from '~/assets/images/pages/auth-v1-mask-light.png'
import authV1Tree2 from '~/assets/images/pages/auth-v1-tree-2.png'
import authV1Tree from '~/assets/images/pages/auth-v1-tree.png'

import { ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useNuxtApp } from 'nuxt/app';

const { locale, t } = useI18n();
const showPassword = ref(false);

// 获取 Nuxt 应用实例以访问插件
const { $toast } = useNuxtApp();

const vuetifyTheme = useTheme()
const authThemeMask = computed(() => {
  return vuetifyTheme.global.name.value === 'light' ? authV1MaskLight : authV1MaskDark
})
const form = ref({
  email: '',
  password: '',
  remember: false,
})

definePageMeta({ layout: 'blank' })

const toggleLang = () => {
  locale.value = locale.value === 'zhHans' ? 'en' : 'zhHans';
};

const router = useRouter();
const loading = ref(false)

/**
 * 用户登录处理函数
 */
const login = async () => {
  // 验证表单
  if (!form.value.email) {
    $toast.error(t('required.username'));
    return;
  }
  if (!form.value.password) {
    $toast.error(t('required.password'));
    return;
  }
  try {
    loading.value = true;
    // 调用登录API
    const response = await $fetch('/api/auth/login', {
      method: 'POST',
      body: {
        username: form.value.email,
        password: form.value.password
      }
    });
    
    if (response.success) {
      // 登录成功，保存令牌和用户信息
      const { token, user } = response.data;
      
      // 使用auth插件设置身份验证状态
      const { $auth } = useNuxtApp();
      $auth.setAuth(token, user);
      
      // 如果选择了"记住我"选项，使用$auth插件保存凭证
      if (form.value.remember) {
        $auth.saveRememberCredentials(form.value.email, token);
      }

      // 显示成功消息
      $toast.success('登录成功！');

      // 登录成功查看是否有redirect参数
      const redirect = router.currentRoute.value.query.redirect;
      if (redirect) {
        router.push(redirect);
      } else {
        // 没有redirect参数，跳转到首页
        router.push('/');
      }
      
    } else {
      // 登录失败处理
      $toast.error(response.message || '登录失败，请检查用户名和密码');
    }
  } catch (error) {
    console.error('登录错误:', error);
    $toast.error('登录过程中发生错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  locale.value = 'zhHans';
});
</script>

<style lang="scss">
@use "@core/scss/template/pages/page-auth";
</style>

<style lang="scss" scoped>
.logo {
  width: 100px;
}
</style>